# -*- coding: utf-8 -*-
"""
Created on Mon Apr 10 18:21:52 2023

@author: ZHOU
"""

import time
from flask import Flask, render_template, request
import threading
import socket
import serial
import serial.tools.list_ports

local_post = 1212
local_ip = None

for i in range(12):
    try:
        s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        s.connect(("8.8.8.8",80))
        local_ip = str(s.getsockname()[0])
        s.close()
        print("Network Enable")
        network_flag = 1
        break
    except:        
        print("Network Error...")
        network_flag = 0
        time.sleep(5)

app = Flask(__name__)

com_rx_buf = ''				# 接收缓冲区
com_tx_buf = ''				# 发送缓冲区
COMM = serial.Serial()		# 定义串口对象
port_list: list				# 可用串口列表
port_select: list			# 选择好的串口

ML307A_RX=''

location_info = '请输入用户名和密码并成功登陆后，刷新网页查看定位信息'
location_info_flag=0
# 无串口返回0，
# 返回可用的串口列表
def get_com_list():
    global port_list
    # a = serial.tools.list_ports.comports()
    # print(a)
    # port_list = list(serial.tools.list_ports.comports())
    port_list = serial.tools.list_ports.comports()
    return port_list


def set_com_port(n=0):
    global port_list
    global port_select
    port_select = port_list[n]
    return port_select.device


# 打开串口
def serial_open(n=0):
    global COMM
    serial_port = set_com_port(n)
    COMM = serial.Serial(serial_port, 115200, timeout=0.01)
    if COMM.isOpen():
        print(serial_port, "open success")
        return 0
    else:
        print("open failed")
        return 255


# 关闭串口
def serial_close():
    global COMM
    COMM.close()
    print(COMM.name + "closed.")


def set_com_rx_buf(buf=''):
    global com_rx_buf
    com_rx_buf = buf


def set_com_tx_buf(buf=''):
    global com_tx_buf
    com_tx_buf = buf


def get_com_rx_buf():
    global com_rx_buf
    return com_rx_buf


def get_com_tx_buf():
    global com_tx_buf
    return com_tx_buf


def thread_com_receive():
    global ML307A_RX
    while True:
        try:
            rx_buf = ''
            rx_buf = COMM.read()  # 转化为整型数字
            if rx_buf != b'':
                time.sleep(0.01)
                rx_buf = rx_buf + COMM.read_all()
                print("串口收到消息:", rx_buf)
                ML307A_RX=str(rx_buf).split("\\r\\n")[1]
            time.sleep(0.01)
        except:
            pass
    pass


# def serial_encode(addr=0, command=0, param1=0, param0=0):
#     buf = [addr, command, param1, param0, 0, 0, 0, 0]
#     print(buf)
#     return buf


def serial_send_command(addr=0, command=0, param1=0, param0=0, data3=0, data2=0, data1=0, data0=0):
    buf = [addr, command, param1, param0, data3, data2, data1, data0]
    COMM.write(buf)
    pass


def serial_init():
    buf = "AT+CG\r\n"
    COMM.write(buf)
    time.sleep(0.05)
    buf = COMM.read_all()
    if buf != "OK\r\n":
        return 254  # 进入调试模式失败

    buf = "AT+CAN_MODE=0\r\n"
    COMM.write(buf)
    time.sleep(0.05)
    buf = COMM.read_all()
    if buf != "OK\r\n":
        return 253          # 进入正常模式失败，模块处于1状态，即环回模式中

    buf = "AT+CAN_BAUD=500000\r\n"
    COMM.write(buf)
    time.sleep(0.05)
    buf = COMM.read_all()
    if buf != "OK\r\n":
        return 253          # 波特率设置失败

    buf = "AT+FRAMEFORMAT=1,0,\r\n"
    COMM.write(buf)
    time.sleep(0.05)
    buf = COMM.read_all()
    if buf != "OK\r\n":
        return 253          # 波特率设置失败

    buf = "AT+ET\r\n"       # 进入透传模式
    COMM.write(buf)
    time.sleep(0.05)
    buf = COMM.read_all()
    if buf != "OK\r\n":
        return 255  # 不是CAN模块

def com_jugg():
    global ML307A_RX
    global location_info
    global location_info_flag
    while True:
        COMM.write("""AT+MUESTATS="radio"\r\n""".encode("UTF-8"))
        time.sleep(0.5)
        if location_info_flag == 1:
            location_info = ML307A_RX.split("""+MUESTATS: "radio",""")[1]
            print(location_info)
        time.sleep(2.5)
        print(1)
    
def init_com():
    global ML307A_RX
    get_com_list()
    len = port_list.__len__()
    device = port_list[0].device
    print(len, device)
    serial_open(0)
    thread1 = threading.Thread(target=thread_com_receive)
    thread1.setDaemon(True)
    thread1.start()
    COMM.write("AT\r\n".encode("UTF-8"))
    time.sleep(0.1)
    print(321)
    if ML307A_RX=="OK":
        print(111)
        com_jugg()


#@app.route('/login/')   # 登录
#def login():
#    return render_template('login.html')

    
@app.route('/', methods=['GET', 'POST'])
def index():
    global location_info_flag
    global location_info
    command_str=''
    if request.method == 'POST':
        c0 = str(request.form.get('send'))
        c1 = str(request.form.get('user'))
        c2 = str(request.form.get('pass'))
        for i in [c0,c1,c2]:
            if i != "None":
                command_str = i
                break
    if command_str == "登陆":
        if str(request.form.get('user'))=="admin" and str(request.form.get('pass'))=="123":
            location_info_flag=1
            print("登陆成功")
        else:
            print("登陆失败")
        
    now_today = time.time()
    time_hour = time.localtime(now_today).tm_hour
    time_min = time.localtime(now_today).tm_min
    time_sec = time.localtime(now_today).tm_sec
    
    if time_hour < 10:
        time_hour = "0"+str(time_hour)
    if time_min < 10:
        time_min = "0"+str(time_min)
    local_time_str = str(time.localtime(now_today).tm_year)+"-"+str(time.localtime(now_today).tm_mon)+"-"+str(time.localtime(now_today).tm_mday)+" "+str(time_hour)+":"+str(time_min)+":"+str(time_sec)
                
    data = {
        '当前时间：': [local_time_str],
        '位置信息：': [location_info],
	        }
    return render_template('index.html',data_dict=data)


def app_run():
    app.run(host=local_ip, port=local_post)
    
if __name__ == "__main__":
    thread0 = threading.Thread(target=app_run)
    thread0.setDaemon(True)
    thread0.start()
    print(123)
    init_com()
